﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jermaine
{
    /// <summary>
    /// 单例接口
    /// </summary>
    public interface ISingleton
    {
        void Initlialize();
    }

    /// <summary>
    /// 单例工厂类
    /// </summary>
    public class SingletonFacotry
    {
        private SingletonFacotry() { }

        private static readonly Dictionary<string, ISingleton> InstanceStorage;

        static SingletonFacotry() {
            InstanceStorage = new Dictionary<string, ISingleton>();
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <typeparam name="TInstance"></typeparam>
        /// <returns></returns>
        public static TInstance GetInstance<TInstance>() where TInstance : ISingleton {
            var type = typeof(TInstance);
            var name = type.FullName;
            TInstance o = default(TInstance);

            try {
                lock (((ICollection)InstanceStorage).SyncRoot) {
                    var existed = InstanceStorage.ContainsKey(name);

                    if (existed) {
                        o = (TInstance)InstanceStorage[name];
                    } else {
                        o = Activator.CreateInstance<TInstance>();
                        o.Initlialize();
                        InstanceStorage.Add(name, o);
                    }
                }
            } catch { }
            return o;
        }
    }
}
